package com.me.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.bbs.anno.RequireLogin;
import com.me.bbs.common.Resp;
import com.me.bbs.common.SessionUtils;
import com.me.bbs.dto.PostDTO;
import com.me.bbs.entity.Post;
import com.me.bbs.entity.User;
import com.me.bbs.exceptions.NoLoginException;
import com.me.bbs.service.IPostService;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lm
 * @since 2023-01-09
 */
@RestController
@RequestMapping("/post")
public class PostController {
    @Resource
    IPostService postService;

    @PostMapping("/create")
    @RequireLogin
    public Resp<?> createPost(@RequestBody Post post, HttpSession session) throws Exception {
        Long uid = (Long) session.getAttribute("user");
        if (uid == null) throw new NoLoginException("未登录！");
        post.setAuthor(uid);
        postService.createPost(post);
        return Resp.success(post.getPostId());

    }

    @GetMapping("/{id}")
    public Resp<?> getPost(@PathVariable Long id) {
        PostDTO post = postService.getPostDto(id);
        return Resp.success(post, "成功");
    }

    @PostMapping("/page")
    public Resp<?> listPostBriefInPage(@RequestParam("current") Long current,
                                       @RequestParam("size") Long size,
                                       @RequestParam(value = "forumId", required = false) Long forumId,
                                       @RequestParam(value = "orderBy", defaultValue = "1") Integer orderBy) {
        Page<PostDTO> dtoPage = new Page<>(current, size);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(forumId != null,Post::getForum, forumId)
                .orderByDesc(Post::getViewCount)
                .orderBy(orderBy == 1, false, Post::getLastReplyAt)
                .orderBy(orderBy == 2, false, Post::getCreateTime);

        Page<PostDTO> postList = postService.getPostList(dtoPage, wrapper);
        return Resp.success(postList, "成功");
    }

    @PostMapping("/listByUser")
    public Resp<?> listByUser(@RequestParam("current") Long current,
                                       @RequestParam("size") Long size,
                                       @RequestParam(value = "userId") Long userId) {
        Page<PostDTO> dtoPage = new Page<>(current, size);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null,Post::getAuthor, userId)
                .orderByDesc(Post::getCreateTime);
        Page<PostDTO> postList = postService.getPostList(dtoPage, wrapper);
        return Resp.success(postList, "成功");
    }

    @PostMapping("/search")
    public Resp<?> searchPost(@RequestParam("current") Long current,
                              @RequestParam("size") Long size,
                              @RequestParam(value = "q") String q,
                              @RequestParam(value = "order",required = false) String order) {
        Page<PostDTO> dtoPage = new Page<>(current, size);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        //可能出现order by字段同名导致不明确，所以采取sql拼接
        String s = StringUtils.camelToUnderline(order);
        wrapper.like(Post::getTitle, q).or().like(Post::getBrief, q).last("order by post." + s + " desc");
        Page<PostDTO> postList = postService.getPostList(dtoPage, wrapper);
        return Resp.success(postList, "成功");
    }

    @PostMapping("/hot")
    public Resp<?> getHotList(@RequestParam(value = "forumId", required = false) Long forumId ) {
        List<Post> list = postService.lambdaQuery().orderByDesc(Post::getCommentCount)
                .eq(forumId!=null, Post::getForum, forumId)
                .last("limit 10")
                .list();
        return Resp.success(list, "成功");
    }
    @DeleteMapping("/{postId}")
    public Resp<?> deletePost(@PathVariable Long postId) {
        boolean res = postService.deletePost(postId);
        if(res)
            return Resp.success();
        return Resp.error("删除时出错");
    }
}
